from PySide6.QtCore import QObject, Signal
import time
import requests
import hashlib  # 用于密码加密

class TicketWorker(QObject):
    result = Signal(dict)
    error = Signal(str)
    finished = Signal()
    login_signal = Signal(dict)  # 登录结果信号：{success: bool, message: str}
    qrcode_signal = Signal(dict)  # 二维码信号，传递包含uuid和image的字典数据

    def __init__(self, config=None):
        super().__init__()
        self.running = False
        self.config = config or {'interval': 5}  # 默认查询间隔5秒
        # 模拟订单数据库
        self.orders_db = [
            {'id': 'OD001', 'train': 'G123', 'seat': '二等座05车12A', 'status': '已支付'},
            {'id': 'OD002', 'train': 'D456', 'seat': '一等座02车08F', 'status': '待支付'}
        ]
        self.session = requests.Session()  # 保持会话用于验证码和登录关联

    def start(self):
        """启动后台查询任务"""
        self.running = True
        self.run_query()

    def stop(self):
        """停止后台查询任务"""
        self.running = False

    def run_query(self):
        """执行车票查询循环"""
        while self.running:
            try:
                tickets_data = self.fetch_tickets()
                self.result.emit(tickets_data)
                time.sleep(self.config['interval'])
            except Exception as e:
                self.error.emit(f'查询失败: {str(e)}')
        self.finished.emit()

    def get_captcha(self):
        """获取验证码图片（需对接12306真实接口）"""
        try:
            captcha_url = 'https://kyfw.12306.cn/passport/captcha/captcha-image64?login_site=E&module=login&rand=sjrand'
            response = self.session.get(captcha_url)
            response.raise_for_status()
            # 解析Base64图片数据并发送信号
            captcha_data = response.json()
            self.login_signal.emit({'type': 'captcha', 'data': captcha_data['image']})
        except requests.exceptions.RequestException as e:
            self.login_signal.emit({'type': 'error', 'message': f'获取验证码失败: {str(e)}'})

    def start_login(self, username, password, captcha):
        """执行实际登录请求（需对接12306真实接口）"""
        try:
            # 密码MD5加密（实际12306使用更复杂加密，此处为示例）
            encrypted_pwd = hashlib.md5(password.encode()).hexdigest()
            
            # 模拟登录请求（替换为真实12306接口地址）
            login_url = 'https://kyfw.12306.cn/passport/web/login'
            payload = {
                'username': username,
                'password': encrypted_pwd,
                'captcha': captcha
            }
            response = self.session.post(login_url, data=payload)
            response.raise_for_status()  # 检查HTTP错误
            
            # 解析响应（根据实际接口返回格式调整）
            # 记录响应内容日志
            print(f'[DEBUG] 响应内容: {response.text}')
            result = response.json()
            if result.get('result_code') == 0:
                # 登录成功，保存会话信息
                self.login_signal.emit({'success': True, 'message': '登录成功'})
            else:
                self.login_signal.emit({'success': False, 'message': result.get('result_message', '登录失败')})
                # 登录失败后自动刷新验证码
                self.get_captcha()
        except requests.exceptions.RequestException as e:
            self.login_signal.emit({'success': False, 'message': f'网络错误: {str(e)}'})
            self.get_captcha()
        except Exception as e:
            self.login_signal.emit({'success': False, 'message': f'系统错误: {str(e)}'})
            self.get_captcha()

    qrcode_status_signal = Signal(dict)  # 二维码状态信号：{status: str, message: str, cookies: dict?}

    def get_qrcode(self):
        """获取二维码数据（对接12306真实接口，返回uuid和二维码图片）"""
        try:
            # 根据接口文档调整请求参数
            qrcode_url = 'https://kyfw.12306.cn/passport/web/create-qr64'
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'Origin': 'https://kyfw.12306.cn',
                'Referer': 'https://kyfw.12306.cn/'
            }
            # 发送POST请求并传递appid参数（接口文档要求）
            response = self.session.post(qrcode_url, headers=headers, data='appid=otn')
            # 记录请求日志
            print(f'[DEBUG] 获取二维码请求URL: {qrcode_url}')
            print(f'[DEBUG] 请求头: {headers}')
            print(f'[DEBUG] 响应状态码: {response.status_code}')
            response.raise_for_status()
            
            # 解析接口返回的uuid和二维码数据（根据文档格式调整）
            # 记录响应内容日志
            print(f'[DEBUG] 响应内容: {response.text}')
            result = response.json()
            if 'uuid' not in result:
                raise Exception('接口未返回uuid')
            if 'image' not in result or not result['image']:
                raise Exception('接口返回的image字段缺失或为空')
            qrcode_data = {
                'uuid': result['uuid'],
                'image': result['image']  # 修正为接口返回的image字段
            }
            print(f'[DEBUG] 发射二维码信号，构造的qrcode_data: {qrcode_data}')  # 新增日志，确认uuid和image字段是否正确传递
            self.qrcode_signal.emit(qrcode_data)  # 发射二维码数据信号
        except requests.exceptions.RequestException as e:
            self.qrcode_signal.emit(None)
            self.error.emit(f'获取二维码网络请求失败: {str(e)}')
        except Exception as e:
            self.qrcode_signal.emit(None)
            self.error.emit(f'解析二维码数据失败（请检查接口返回格式）: {str(e)}')

    def check_qrcode_status(self, uuid):
        """检查二维码登录状态（对接接口文档中的uamauthclient接口）"""
        try:
            # 根据接口文档构造状态查询URL
            status_url = 'https://kyfw.12306.cn/otn/uamauthclient'
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'Origin': 'https://kyfw.12306.cn',
                'Referer': 'https://kyfw.12306.cn/'
            }
            # 发送状态查询请求（文档示例使用tk参数）
            response = self.session.post(status_url, headers=headers, data=f'tk={uuid}')
            response.raise_for_status()
            
            # 解析接口返回的登录状态（根据文档格式调整）
            # 记录响应内容日志
            print(f'[DEBUG] 响应内容: {response.text}')
            result = response.json()
            status_info = {
                'status': 'pending',
                'message': '等待扫描...'
            }
            if result.get('result_code') == 0 and 'username' in result:
                # 登录成功，提取cookie信息
                cookies = requests.utils.dict_from_cookiejar(self.session.cookies)
                status_info = {
                    'status': 'success',
                    'message': '登录成功！',
                    'cookies': cookies }
                self.user_cookies = cookies  # 缓存登录cookie
                self.start_cookie_check()  # 启动cookie定时校验
            elif result.get('result_code') == 1:
                status_info['status'] = 'scanned'
                status_info['message'] = '二维码已扫描，请确认登录'
            
            self.qrcode_status_signal.emit(status_info)
        except requests.exceptions.RequestException as e:
            self.qrcode_status_signal.emit({'status': 'error', 'message': f'状态查询失败: {str(e)}'})
        except Exception as e:
            self.qrcode_status_signal.emit({'status': 'error', 'message': f'解析状态响应失败: {str(e)}'})

    def fetch_tickets(self):
        """实际调用12306接口获取车票数据（需后续实现具体请求逻辑）"""
        # 示例返回数据
        # 返回包含模拟订单数据的结果
        return {
            'trains': [
                {'number': 'G123', 'from': '北京', 'to': '上海', 'time': '08:00-12:00', 'seats': {'二等座': 10}}
            ],
            'orders': self.orders_db,  # 传递当前订单数据
            'stations': self.stations  # 传递车站数据用于自动补全
        }

    def cancel_order(self, order_id):
        """处理取消订单请求（需后续对接实际接口）"""
        try:
            # 实际更新模拟订单数据
            for order in self.orders_db:
                if order['id'] == order_id:
                    order['status'] = '已取消'
                    print(f"模拟取消订单成功：{order_id}")
                    break
            else:
                print(f"未找到订单：{order_id}")
        except Exception as e:
            self.error.emit(f'取消订单失败: {str(e)}')